package com.dq.health.security;

import com.dq.health.dto.response.menu.SysMenuTreeInfo;
import com.dq.health.entity.user.UserBaseInfo;
import com.dq.health.utils.data.Tree;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class UserDetailsModel implements UserDetails {

    private static final long serialVersionUID = 1998415861886139915L;

    private UserBaseInfo sysUser;

    private String sessionId;

    private Tree<SysMenuTreeInfo> menuTreeInfos;

    public UserBaseInfo getSysUser() {
        return sysUser;
    }

    public void setSysUser(UserBaseInfo sysUser) {
        this.sysUser = sysUser;
    }

    public String getSessionId() {
        return sessionId;
    }

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    public Tree<SysMenuTreeInfo> getMenuTreeInfos() {
        return menuTreeInfos;
    }

    public void setMenuTreeInfos(Tree<SysMenuTreeInfo> menuTreeInfos) {
        this.menuTreeInfos = menuTreeInfos;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Set<String> dbAuthSet = new HashSet<String>();
        if (sysUser.getRoleId() != null) {
            // 获取角色
            dbAuthSet.add(sysUser.getRoleId().toString());
            // 获取权限
            dbAuthSet.add(sysUser.getRoleId().toString());
        }

        return AuthorityUtils.createAuthorityList(dbAuthSet.toArray(new String[0]));
    }

    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUserName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return sysUser.getUserStatus() == 1;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj instanceof UserDetailsModel) {
            return sysUser.getUserId().equals(((UserDetailsModel)obj).getSysUser().getUserId());
        }
        return false;
    }

    @Override
    public int hashCode() {
        return sysUser.getUserId() != null ? sysUser.getUserId().hashCode() : 0;
    }

}
